<template>
  <div class="z-operate-button">
    <a-space>
      <span class="operate-button"
            v-for="(item,index) in data"
            :key="index"
            @click="handleDataButtonClick(item,index)">
        {{ item.name }}
        <a-divider v-if="index<hasPermissionData.length-1"
                   type="vertical" />
      </span>
      <a-dropdown v-if="hasPermissionData.length>3"
                  placement="bottomCenter">
        <span class="operate-button">更多</span>
        <a-menu slot="overlay">
          <a-menu-item v-for="(more,index) in moreData"
                       :key="index"
                       @click="handleMoreDataButtonClick(more,index)">
            <span>{{ more.name }}</span>
          </a-menu-item>
        </a-menu>
      </a-dropdown>
    </a-space>
  </div>
</template>
<script>

import PropTypes from '@zh/common-utils/prop-types'

export default {
  name: 'ZOperateButton',
  props: {
    operateData: {
      type: Array,
      default: () => []
    },
    extraData: PropTypes.object.def({})
  },
  data () {
    return {
      data: [],
      moreData: []
    }
  },
  computed: {
    // 根据按钮权限过滤数据，只展示有权限的按钮
    hasPermissionData () {
      // hasPermission在zongheng-base中为Vue.prototype全局函数，这里只是简单模拟
      return this.operateData.filter(item => {
        return true
        // return !this.hasPermission || !item.code || this.hasPermission(item.code)
      })
    }
  },
  watch: {
    operateData () {
      this.initData()
    }
  },
  created () {
    this.initData()
  },
  methods: {
    handleMoreDataButtonClick (more, index) {
      if (more.fn) {
        more.fn(this.extraData)
      }
      this.$emit('operateButtonClick', { item: more, index: index, extraData: this.extraData })
    },
    handleDataButtonClick (item, index) {
      item.fn && item.fn(this.extraData)
      this.$emit('operateButtonClick', { item: item, index: index, extraData: this.extraData })
    },
    initData () {
      this.data = this.hasPermissionData.filter((item, index) => {
        if (this.hasPermissionData.length > 3) {
          return index < 2
        } else {
          return index < 3
        }
      })
      this.setMoreButtonData()
    },
    setMoreButtonData () {
      if (this.hasPermissionData.length > 2) {
        this.moreData = this.hasPermissionData.filter((item, index) => {
          return index >= 2
        })
      }
    }
  }
}
</script>
<style lang="less" scoped>
.z-operate-button {
  width: 100%;
  display: flex;
  justify-content: space-evenly;
  .operate-button {
    font-size: var(--font-size-def);
    color: #1890ff;
    cursor: pointer;
  }
}
</style>